package com.sweet.store;

import com.sweet.entity.User;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import org.mapdb.DB;
import org.mapdb.DBMaker;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by sweet on 2019/1/15.
 * ---------------------------
 */
public class FriendsStore implements ITransaction {

  private static final FriendsStore FRIENDS_STORE = new FriendsStore();
  private static final String BASE_PATH = "db/";
  private static final String FRIENDS_DB_PATH = BASE_PATH + "friends.db";
  private static final DB FRIENDS_DB = DBMaker.newFileDB(new File(FRIENDS_DB_PATH)).closeOnJvmShutdown().make();

  private static final Map<String, String> FRIENDS_MAP = FRIENDS_DB.getTreeMap("friends-map");

  public static FriendsStore instance() {
    return FRIENDS_STORE;
  }

  private FriendsStore() {
  }

  public Future<Void> addFriend(String uid, String friendId, Vertx vertx) {
    Future<Void> future = Future.future();
    vertx.executeBlocking(f -> {
      JsonArray friends = new JsonArray(FRIENDS_MAP.getOrDefault(uid, "[]"));
      friends.add(friendId);
      FRIENDS_MAP.put(uid, friends.encode());
      f.complete();
    }, future);
    return future;
  }

  @Override
  public void commit() {
    FRIENDS_DB.commit();
  }

  @Override
  public void close() {
    commit();
    FRIENDS_DB.close();
  }

  public Future<Boolean> findFriend(String uid, User friend) {
    Future<Boolean> future = Future.future();
    JsonArray friendArray = new JsonArray(FRIENDS_MAP.getOrDefault(uid, "[]"));
    future.complete(friendArray.contains(friend.getId()));
    return future;
  }
}
